package com.yiran.service.serviceImp;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yiran.mapper.UserMapper;
import com.yiran.pojo.Result;
import com.yiran.pojo.User;
import com.yiran.service.UserService;
import com.yiran.utils.EncryptUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.NoSuchAlgorithmException;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Override
    public User register(String username, String password) throws NoSuchAlgorithmException {
       //1  查询数据库查看账号是否重复
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        User one = getOne(wrapper.eq(User::getUsername, username));
        if(one!=null){
            log.info("账号存在！注册失败");
            throw new RuntimeException("账号存在");
        }
        //不存在，则可以注册，先生成盐，再通过盐和密码生成加密的密码
        String salt = EncryptUtils.getSalt();
        String encrypt = EncryptUtils.encrypt(salt, password);

        //设置用户数据
        User user = new User();
         user.setUsername(username);
         user.setPassword(encrypt);
         user.setSalt(salt);
         //将用户写入数据库
        boolean save = save(user);
        if(save){
            return user;
        }
        return null;
    }

    @Override
    public User login(String username, String password) throws NoSuchAlgorithmException {
        User one = getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
        if(one==null){
            log.info("不存在用户！");
            throw new RuntimeException("不存在用户!");
        }
        String encrypt = EncryptUtils.encrypt(one.getSalt(), password);
        boolean equals = encrypt.equals(one.getPassword());
        if(equals){
            //生成令牌
            one.setPassword(null);
            one.setSalt(null);
            return one;
        }
        return null;
    }
}

